package com.atguigu.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Enumeration;
@WebServlet(
        urlPatterns = "/servlet1",
        initParams = {
                @WebInitParam(name="keya",value="valuea"),
                @WebInitParam(name="keyb",value="valueb")
        }
)
public class Servlet1 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletConfig servletConfig = getServletConfig();
        //获取初始配置信息即可
        //根据参数名获取参数值
        String keya = servletConfig.getInitParameter("keyaa");
        System.out.println("key:"+keya);


        //获取所有参数名  iterator
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        //hasMoreElements 判断是否还有元素，如果有返回true，没有返回false
        while (initParameterNames.hasMoreElements()) {
            //nextElement 取出下一个元素，向下移动游标
            String name = initParameterNames.nextElement();
            System.out.println(name+":"+getInitParameter(name));

        }


        System.out.println("----------------------------------------------------------------------------");

        //获取servletContext
        ServletContext servletContext = getServletContext();
        ServletContext servletContext1 = servletConfig.getServletContext();
        ServletContext servletContext2 = req.getServletContext();

        System.out.println(servletContext == servletContext1);
        System.out.println(servletContext == servletContext2);
        System.out.println(servletContext1 == servletContext2);

        String encoding = servletContext1.getInitParameter("encoding");
        System.out.println("encoding:"+encoding);

        Enumeration<String> attributeNames = servletContext1.getInitParameterNames();

        while (attributeNames.hasMoreElements()) {

            String pname = attributeNames.nextElement();
            System.out.println(pname+":"+getServletContext().getInitParameter(pname));

        }
        servletContext1.setAttribute("ka","va");
       /* servletContext1.setAttribute("sa","vaa");//向域中存储或修改数据
        Object ka = servletContext1.getAttribute("ka");
        servletContext1.removeAttribute("ka");//从域中删除数据*/
        //servletContext1.removeAttribute("ka");
        servletContext1.setAttribute("ka", "vaa");

    }



}
